package com.study.demo.ui.imagepreview;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.support.annotation.NonNull;

import com.facebook.cache.common.CacheKey;
import com.facebook.imagepipeline.cache.DefaultCacheKeyFactory;
import com.facebook.imagepipeline.core.ImagePipelineFactory;
import com.facebook.imagepipeline.request.ImageRequest;
import com.stduy.injector.PerActivity;
import com.study.demo.components.okhttp.OkHttpHelper;
import com.study.demo.util.ConfigUtil;
import com.study.demo.util.FormatUtil;
import com.study.demo.util.StringUtil;
import com.study.demo.util.ToastUtil;

import java.io.File;
import java.io.InputStream;

import javax.inject.Inject;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okio.BufferedSink;
import okio.Okio;

/**
 * Created by sll on 2016/4/29.
 */
@PerActivity
public class ImagePreviewPresenter implements ImagePreviewContract.Presenter {

    private String imageUrl;
    private OkHttpHelper mOkHttpHelper;
    private Context mContext;

    @Inject
    public ImagePreviewPresenter(OkHttpHelper okHttpHelper, Context context) {
        mOkHttpHelper = okHttpHelper;
        mContext = context;
    }

    @Override
    public void saveImage(final String url) {
        this.imageUrl = url;
        Observable.just(url)

                .map(this::convertStringToInputStream)
                .map(this::convertInputStreamToFile)
                .map(this::convertFileToFile)
                .doOnNext(this::doOnNext)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(this::onRequestSuccess);
    }

    private InputStream convertStringToInputStream(String url) {
        return getImageBytesFromLocal(Uri.parse(url));
    }

    private File convertInputStreamToFile(InputStream inputStream) {
        if (inputStream != null) {
            String fileName = FormatUtil.getFileNameFromUrl(imageUrl);
            File target = new File(ConfigUtil.getPicSavePath(mContext), fileName);
            if (target.exists()) {
                return target;
            }
            try {
                BufferedSink sink = Okio.buffer(Okio.sink(target));
                sink.writeAll(Okio.source(inputStream));
                sink.close();
                return target;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    private File convertFileToFile(File file) {
        if (file != null && file.exists()) {
            return file;
        }
        try {
            mOkHttpHelper.httpDownload(imageUrl, file);
            return file;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private void doOnNext(File file) {
        if (file != null && file.exists()) {
            scanPhoto(file);
        }
    }

    private void onRequestSuccess(File file) {
        if (file != null && file.exists()) {
            ToastUtil.showToast("保存成功");
        } else {
            ToastUtil.showToast("保存失败，请重试");
        }
    }

    private InputStream getImageBytesFromLocal(Uri loadUri) {
        if (loadUri == null) {
            return null;
        }
        CacheKey cacheKey = DefaultCacheKeyFactory.getInstance()
                .getEncodedCacheKey(ImageRequest.fromUri(loadUri), null);
        try {
            if (ImagePipelineFactory.getInstance().getMainFileCache().hasKey(cacheKey)) {
                return ImagePipelineFactory.getInstance()
                        .getMainFileCache()
                        .getResource(cacheKey)
                        .openStream();
            }
            if (ImagePipelineFactory.getInstance().getSmallImageFileCache().hasKey(cacheKey)) {
                return ImagePipelineFactory.getInstance()
                        .getSmallImageFileCache()
                        .getResource(cacheKey)
                        .openStream();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private void scanPhoto(File file) {
        Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        Uri contentUri = Uri.fromFile(file);
        mediaScanIntent.setData(contentUri);
        mContext.sendBroadcast(mediaScanIntent);
    }

    @Override
    public void copyImagePath(String url) {
        StringUtil.copy(mContext, url);
    }

    @Override
    public void attachView(@NonNull ImagePreviewContract.View view) {

    }

    @Override
    public void detachView() {

    }
}
